import '../../scss/task.scss'
import React from 'react'
import {commonApi} from '../../api/common'
import {userApi} from '../../api/user'
import _ from '../../../lib/lodash'

export default React.createClass({
    getInitialState() {
        return {completeList: {}, receiveList: {}, taskInfo: null}
    },
    componentDidMount() {
        this.getPlayerTask()
    },
    getPlayerTask() {
        let self = this
        userApi.getPlayerTask(function(err, data) {
            self.setState({completeList: data.completeList, receiveList: data.receiveList, taskInfo: null})
        })
    },
    selectTask(taskId) {
        var self = this
        commonApi.getTaskInfo({
            taskId: taskId
        }, function(err, data) {
            self.setState({taskInfo: data})
        })
    },
    completeTask(taskId) {
        var self = this
        commonApi.completeTask({
            taskId: taskId
        }, function(err, data) {
            if (err === 0) {
                self.getPlayerTask()
            }
        })
    },
    render() {
        let self = this
        let completeListNode = []
        let receiveListNode = []
        let taskNode
        if (this.state.completeList) {
            _.forEach(this.state.completeList, function(n, key) {
                completeListNode.push(
                    <button className="item" key={key} onClick={self.selectTask.bind(self, key)}>{key}</button>
                )
            });
        }
        if (this.state.receiveList) {
            _.forEach(this.state.receiveList, function(n, key) {
                receiveListNode.push(
                    <button className="item" key={key} onClick={self.selectTask.bind(self, key)}>{key}</button>
                )
            });
        }

        if (this.state.taskInfo) {
            taskNode = <div className="taskInfo">
                <div className="title">{this.state.taskInfo.name}</div>
                <div className="taskContent">{this.state.taskInfo.desc}</div>
                <div className="bottom">
                    <button onClick={this.completeTask.bind(this, this.state.taskInfo.templateId)}>完成任务</button>
                </div>
            </div>
        }
        return <div id="task" className="flex d-column">
            <div className="flex-g-1">
                <div className="head">
                    <div className="title">任务</div>
                </div>
                <div>已经完成的任务</div>
                <div className="flex wrap">{completeListNode}</div>
                <div>接受的任务</div>
                <div className="flex wrap">{receiveListNode}</div>
            </div>
            {taskNode}
        </div>
    }
})
